package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.SetMealService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

@RestController(value = "anminDishController")
@Slf4j
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private RedisTemplate redisTemplate;
    // 根据分类id查询菜品
    @GetMapping("/list")
    public Result<List<Dish>> GetById(Long categoryId){
        List<Dish> list=dishService.GetById(categoryId);
        return Result.success(list);
    }


    // 新增菜品
    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品{}",dishDTO);
        dishService.save(dishDTO);
        //清理缓存
        String key="dish_"+dishDTO.getCategoryId();
        redisTemplate.delete(key);
        return Result.success();
    }

    //分页查询
    @GetMapping("/page")
    public  Result page(DishPageQueryDTO dishPageQueryDTO){
        log.info("分页查询：{}",dishPageQueryDTO);
        PageResult pageResult=dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    // 批量删除菜品
    @DeleteMapping()
    public  Result delete(@RequestParam List<Long> ids){
        log.info("批量删除：{}",ids);
        dishService.delete(ids);
        //清理缓存
        cleanCache("dish_*");
        return Result.success();
    }

    //设置菜品停售，起售
    @PostMapping("/status/{status}")
    public  Result startOrStop(@PathVariable Integer status,long id){
        log.info("设置菜品状态：{}",status);
        dishService.startOrStop(status,id);
        //清理缓存
        cleanCache("dish_*");
        return Result.success();
    }

    //根据id查询菜品
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id){
        log.info("根据id查询菜品：{}",id);
        DishVO dishvo=dishService.getById(id);
        return Result.success(dishvo);
    }
    //修改菜品
    @PutMapping
    public  Result updateDish(@RequestBody DishDTO dishDTO){
        log.info("修改菜品；{}",dishDTO);
        dishService.updateDish(dishDTO);
        //清理缓存
        cleanCache("dish_*");
        return Result.success();
    }

    //清理缓存
    private void cleanCache(String pattern){
        Set sets = redisTemplate.keys(pattern);
        redisTemplate.delete(sets);

    }

}
